from beaker.session import SessionMiddleware
import web
from web import form

log_in = form.Form(
            form.Textbox("login", form.notnull, description="User name"),
            form.Password("password", form.notnull, description="Password")
        )
        
def logged(session):
    if "logeddin" in session:
        if session["logeddin"] == 1:
            return True
    return False

urls = (
    '/', 'index',
    '/logout', 'logout',)

users = {"sl": "123"}

class index:
    def GET(self):
        web.header("Content-Type","text/html; charset=utf-8")
        session = web.ctx.environ['beaker.session']
        if logged(session):
            print "U logged as <b>%s</b>"%session["username"]
            print "<a href='/logout'>logout</a>"
        else:
            print "<form name='main' method='post'> "+ log_in.render() + "<input type='submit' />"
        
    def POST(self):
        session = web.ctx.environ['beaker.session']
        i = web.input()
        if i.login in users and users[i.login] == i.password:
            session['logeddin'] = 1
            session['username'] = i.login
            session.save()
        web.seeother("/")
            
class logout:
    def GET(self):
        session = web.ctx.environ['beaker.session']
        session.invalidate()
        web.seeother("/")
        """
        or
        session.delete()
        session.save()
        """
def session_mw(app):
    return SessionMiddleware(app, key = "sid")

if __name__ == "__main__":
    web.run(urls, globals(), *(web.reloader, session_mw))
